<!-- 台账字段库 -->
<template>
  <div class='fieldList'>
    <div class="fieldList_titleList">
      <span v-for="item in titleList" @click="changeTable(item)" :key="item.name"
        :class="['fieldList_title',item.selected?'actived':'']">{{item.name}}</span>
    </div>
    <div>
      <Table ref="TableHeight" :max-height="onresizeHeight" :columns="columns" :data="data">
      </Table>
      <!-- 分页 -->
      <div class="pagePublicStyle" v-show="pageData.total > 0">
        <div class="totalCount"> 当前第 {{ pageData.current }} 页， 当前第
          {{ (pageData.current - 1) * pageData.rows + 1 }} 条到第
          {{ pageData.current * pageData.rows > pageData.total ? pageData.total : pageData.current * pageData.rows}}
          条， 共 {{ pageData.total }} 条
        </div>
        <Page :total="pageData.total" :current="pageData.current"
          :page-size-opts="pageData.pageSizeOpts" @on-change="pageOnChangeFun"
          @on-page-size-change="pageOnPageSizeChangeFun" show-elevator placement="top"
          show-sizer show-total />
      </div>
    </div>
    <Modal v-model="modal" title="编辑客户资料字段" footer-hide width="600" :styles="{top: '20px'}">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="150">
        <FormItem label="字段名称" prop="fieldValue">
          <Input type="text" v-model="formValidate.fieldValue" disabled
            placeholder="请输入字段名称"></Input>
        </FormItem>
        <FormItem label="字段属性" prop="fieldType">
          <Select v-model="formValidate.fieldType" placeholder="请选择"
            class="cityConfigArea_moudle_select" disabled>
            <Option v-for="item in fieldAttrSort" :key="item.name" :value="item.value">
              {{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="显示端口" prop="postIdList" class="dispaly_port">
          <div class="item_warp">
            <span class="item_title">APP顾问端:</span>
            <CheckboxGroup v-model="formValidate.postIdList">
              <Checkbox :label="Number(item.portId)" v-for="(item,index) in appPostList"
                :key="index" disabled>{{item.portName}}</Checkbox>
            </CheckboxGroup>
          </div>
          <div class="item_warp">
            <span class="item_title">管理后台:</span>
            <CheckboxGroup v-model="formValidate.postIdList">
              <Checkbox :label="Number(item.portId)" v-for="(item,index) in WebPostList"
                :key="index" disabled>{{item.portName}}</Checkbox>
            </CheckboxGroup>
          </div>
        </FormItem>
        <FormItem label="是否必填" prop="ifRequired">
          <Radio-group v-model="formValidate.ifRequired">
            <Radio label="1" :disabled="isdisabledFieldtype">是</Radio>
            <Radio label="2" :disabled="isdisabledFieldtype">否</Radio>
          </Radio-group>
        </FormItem>
        <!-- <FormItem label="是否公司统一要求" prop="companyRules">
             <Radio-group v-model="formValidate.companyRules">
               <Radio label="1">是</Radio>
               <Radio label="2">否</Radio>
            </Radio-group>  
          </FormItem> -->
        <FormItem label="信息分类" prop="infoType">
          <Select v-model="formValidate.infoType" placeholder="请选择"
            class="cityConfigArea_moudle_select" :disabled='isdisabledFieldtype'>
            <Option v-for="item in messageSort" :key="item.name" :value="item.value">
              {{item.name}}</Option>
          </Select>
        </FormItem>
        <FormItem label="状态" prop="validate">
          <Radio-group v-model="formValidate.validate">
            <Radio label="1" :disabled='isdisabledFieldtype'>启用</Radio>
            <Radio label="2" :disabled='isdisabledFieldtype'>禁用（对已使用该字段的台账无作用）</Radio>
          </Radio-group>
        </FormItem>
        <FormItem label="字段描述" prop="fieldDescription">
          <Input type="textarea" :autosize="{minRows: 2,maxRows: 4}" maxlength="100"
            v-model="formValidate.fieldDescription" placeholder="请输入字段描述(不能超过100字符)"></Input>
        </FormItem>
        <FormItem label="类型" prop="inputType">
          <Radio-group v-model="formValidate.inputType" disabled>
            <Radio label="2" :disabled="formValidate.inputType != 2||isdisabledFieldtype">单选
            </Radio>
            <Radio label="3" :disabled="formValidate.inputType != 3||isdisabledFieldtype">多选
            </Radio>
            <Radio label="1" :disabled="formValidate.inputType != 1||isdisabledFieldtype">填空
            </Radio>
          </Radio-group>
        </FormItem>
        <FormItem label="提示文案" prop="fieldTitle">
          <Input type="text" v-model="formValidate.fieldTitle" disabled></Input>
        </FormItem>
        <div v-if="formValidate.inputType !== '1'" class="divider">
          <FormItem label="样式" prop="styleTypeName">
            <Input type="text" v-model="formValidate.styleTypeName" disabled></Input>
          </FormItem>
          <FormItem label="选项列表（多个选项请回车（换行））"
            :prop="formValidate.ifEdit == 2?'aa':'optionString'" class="tabTop">
            <Input type="textarea" :autosize="{minRows: 2,maxRows: 5}"
              :disabled="formValidate.ifEdit == 2||isdisabledFieldtype"
              v-model="formValidate.optionString" placeholder="请输入选项，多个选项请回车（换行）"></Input>
          </FormItem>
        </div>

        <div v-if="formValidate.inputType === '1'" class="divider">
          <FormItem label="填空类型" prop="fieldTextFormatMess">
            <Input type="text" class="lineLabelInput"
              v-model="formValidate.fieldTextFormatMess" disabled></Input>
            <Checkbox v-model="formValidate.ifDisplayUnit" class="lineLabel"
              :disabled='isdisabledFieldtype'>
              <span class="lineLabelSpan">单位</span>
              <Input type="text" class="lineLabelInput" maxlength="10"
                v-model="formValidate.fieldUnit" :disabled='isdisabledFieldtype'></Input>
            </Checkbox>
          </FormItem>
          <!-- <FormItem label="单位" :label-width="20-0" class="lineLabel">
                <span>单位</span>
                <Input type="text" v-model="formValidate.fieldUnit"></Input>
             </FormItem> -->
          <FormItem label="样式" prop="styleTypeName">
            <Input type="text" v-model="formValidate.styleTypeName" disabled></Input>
          </FormItem>
        </div>

        <FormItem class="cityList_moudle_footer">
          <Button class="moudle_cancelButton" @click="modal = false">取消</Button>
          <Button :loading="saveloading" type="primary"
            @click="saveTableDatail('formValidate')">确定</Button>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
  import standBookList from '@/biz/standBookList/standBookList'
  export default {
    components: {},
    filters: {},
    data() {
      return {
        titleList: [
          { name: '全部', selected: true, value: '' },
          { name: '基本信息', selected: false, value: '1' },
          { name: '服务信息', selected: false, value: '2' },
          { name: '置业需求', selected: false, value: '3' },
          { name: '客户画像', selected: false, value: '4' },
        ],
        appPostList: [
          { portId: 1, portName: '客户新增' },
          { portId: 2, portName: '客户编辑' },
          { portId: 3, portName: '客户详情' },
        ],
        WebPostList: [
          { portId: 4, portName: '客户列表' },
          { portId: 5, portName: '客户详情' },
        ],
        onresizeHeight: 0,
        pageData: {
          total: 0,
          current: 1,
          rows: 10,
          pageSizeOpts: [10, 20, 30, 40, 50],
        },

        columns: [
          {
            title: '字段名称',
            key: 'fieldValue',
            minWidth: 120,
            align: 'center',
            render(h, params) {
              let sd = params.row.fieldValue
              return h('div', [
                params.row.fieldDescription ?
                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'right',
                    },
                  },
                  [
                    h('span', params.row.fieldValue),
                    h('Icon', {
                      props: {
                        type: 'ios-help',
                      },
                      style: {
                        fontWeight: '700',
                        fontSize: '14px',
                        color: 'red',
                        border: '1px solid red',
                        borderRadius: '50%',
                        marginLeft: '5px',
                      },
                    }),
                    h(
                      'div',
                      {
                        slot: 'content',
                      },
                      params.row.fieldDescription
                    ),
                  ]
                ) :
                h('span', params.row.fieldValue),
              ])
            },
          },
          {
            title: '是否必填',
            key: 'ifRequired',
            minWidth: 120,
            align: 'center',
            render(h, params) {
              return h('div', params.row.ifRequired == 1 ? '必填' : '选填')
            },
          },
          // {
          //   title: "公司统一要求",
          //   key: "companyRules",
          //   minWidth: 120,
          //   align:'center',
          //   render(h,params){
          //     return h("div",params.row.companyRules == 1?'是':'否')
          //   }
          // },
          {
            title: '字段属性', //1: 系统字段 2: 默认字段 3:扩展字段
            key: 'fieldType',
            minWidth: 120,
            align: 'center',
            render(h, params) {
              return h(
                'div',
                params.row.fieldType == 1 ?
                '系统字段' :
                params.row.fieldType == 2 ?
                '默认字段' :
                params.row.fieldType == 3 ?
                '扩展字段' :
                '-'
              )
            },
          },
          {
            title: '类型',
            key: 'inputType',
            minWidth: 120,
            align: 'center',
            render(h, params) {
              let inputType = params.row.inputType
              return h(
                'div',
                inputType == 1 ? '填空' : inputType == 2 ? '单选' : '多选'
              )
            },
          },
          {
            title: '状态',
            key: 'validate',
            minWidth: 120,
            align: 'center',
            render(h, params) {
              return h('div', params.row.validate == 1 ? '启用' : '禁用')
            },
          },
          {
            title: '样式',
            key: 'styleType',
            minWidth: 120,
            align: 'center',
            render: (h, params) => {
              return h('div', this.styleType[params.row.styleType - 1])
            },
          },
          {
            title: '内容',
            key: 'content',
            minWidth: 230,
            align: 'center',
            render: (h, params) => {
              let { inputType, content, fieldUnit, options } = params.row
              return h(
                'div',
                inputType == 1 ?
                content + (!!fieldUnit ? `, 单位为${fieldUnit}` : '') :
                options && options.length > 0 ?
                options.join('、') :
                ''
              )
            },
          },
          {
            title: '信息分类',
            key: 'infoType',
            minWidth: 120,
            align: 'center',
            render: (h, params) => {
              return h(
                'div',
                this.messageSort[params.row.infoType - 1] ?
                this.messageSort[params.row.infoType - 1].name :
                '-'
              )
            },
          },
          {
            title: '操作',
            minWidth: 120,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      //disabled:params.row.ifEdit == 2,
                      type: 'text',
                    },
                    on: {
                      click: (e) => {
                        e.stopPropagation()
                        this.editChannel(params.row) //点击事件
                      },
                    },
                  },
                  '编辑'
                ),
              ])
            },
          },
        ],
        data: [],
        modal: false,
        formValidate: {
          fieldDescription: '',
        },
        ruleValidate: {
          fieldValue: [
            { required: true, message: '请输入字段名称', trigger: 'blur' },
          ],
          ifRequired: [{ required: true }],
          // companyRules: [{ required: true }],
          infoType: [{ required: true }],
          inputType: [{ required: true, message: '请输入类型' }],
          fieldTextFormatMess: [{ required: true, message: '请输入类型' }],
          validate: [{ required: true }],
          fieldTitle: [{ required: true }],
          styleTypeName: [{ required: true, message: '请输入填空类型' }],
          optionString: [
          {
            required: true,
            message: '请输入不超过100字符的选项列表',
            trigger: 'blur',
          }, ],
          postIdList: [{ required: true }],
          fieldType: [
            { required: true, message: '请选择字段属性', trigger: 'blur' },
          ],
        },
        styleType: [
          '单行平铺',
          '多行平铺',
          '平铺多级联动',
          '弹框列表',
          '弹框多级联动',
        ],
        messageSort: [
          { name: '基本信息', value: '1' },
          { name: '服务信息', value: '2' },
          { name: '置业需求', value: '3' },
          { name: '客户画像', value: '4' },
        ],
        fieldAttrSort: [
          { name: '系统字段', value: '1' },
          { name: '默认字段', value: '2' },
          { name: '扩展字段', value: '3' },
        ],
        infoType: '',
        isdisabledFieldtype: false,
        saveloading: false,
      }
    },
    computed: {},
    watch: {
      // "formValidate.fieldDescription"(newValue,oldValue){
      //  if(newValue)console.log(newValue,newValue.length)
      //    if(newValue  && newValue.length>100){
      //      console.log(5555555)
      //      let sd = newValue.slice(0,100);
      //      console.log(sd)
      //      this.$set(this.formValidate,'fieldDescription',sd)
      //     }
      //}
    },
    methods: {
      initDate() {
        this.$nextTick(() => {
          this.onresizeHeight =
            window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 80
        })
      },
      //获取台账列表
      getTableList() {
        standBookList
          .getStandingBookGetAll({
            page: this.pageData.current,
            rows: this.pageData.rows,
            infoType: this.infoType,
          })
          .then((res) => {
            console.log('获取台账列表', res)
            if (!res || res.pageData.length < 1) return (this.data = [])
            this.data = res.pageData
            this.pageData.total = res.total - 0
          })
      },
      //获取字段的详细信息
      getTableDatail(standingBookCompanyId) {
        if (!standingBookCompanyId) return
        this.formValidate = {}
        standBookList
          .detailStandingBook({ standingBookCompanyId })
          .then((res) => {
            console.log('获取详细信息', res)
            if (res.inputType == 1) {
              res.fieldTitle = '请输入' //提示文案
              res.fieldTextFormatMess = [
                '文本',
                '整数',
                '小数',
                '文本区间',
                '整数区间',
                '小数区间',
                '时间选择器',
              ][res.fieldTextFormat - 1]
            } else {
              res.fieldTitle = '请选择' //提示文案
            }
            //选项列表改成string  以逗号隔开
            res.optionString =
              res.options && res.options.length > 0 ?
              res.options.join(',').replace(/,/g, '\n') :
              ''
            //单位字段转成boolen值
            res.ifDisplayUnit = res.ifDisplayUnit == 1
            //样式
            res.styleTypeName = this.styleType[res.styleType - 1]
            this.formValidate = res
            if (res.fieldType && res.fieldType == 1) {
              this.isdisabledFieldtype = true
            } else {
              this.isdisabledFieldtype = false
            }
          })
      },
      //字段修改保存
      saveTableDatail() {
        this.$refs.formValidate.validate((valid) => {
          if (valid) {
            console.log(this.formValidate, this.formValidate.optionString.length)
            this.saveloading = true
            if (this.formValidate.optionString.length > 0) {
              this.formValidate.options = this.formValidate.optionString
                .replace(/\n/g, ',')
                .split(',')
            } else {
              this.formValidate.options = []
            }
            this.formValidate.fieldUnit = this.formValidate.fieldUnit || ''
            this.formValidate.ifDisplayUnit = this.formValidate.ifDisplayUnit ?
              1 :
              2

            standBookList
              .updateStandingBook(this.formValidate)
              .then((res) => {
                this.saveloading = false
                this.$Message.success('修改成功')
                this.modal = false
                this.getTableList()
              })
              .catch((err) => {
                this.saveloading = false
                this.$Message.error(err)
              })
          }
        })
      },
      pageOnChangeFun(pages) {
        if (pages != 1 || this.pageData.current != 1) {
          this.pageData.current = pages
          this.getTableList()
        }
      },
      pageOnPageSizeChangeFun(rows) {
        this.pageData.rows = rows
        this.pageData.current = 1
        this.getTableList()
      },
      //点击编辑按钮
      editChannel(data) {
        this.getShowPort(data)

        this.modal = true
      },
      //获取显示端口
      getShowPort(data) {
        standBookList.standingbookShowPort({}).then(async (res) => {
          console.log('获取显示端口', res)
          this.appPostList = res.filter((item) => item.portType == 1)
          this.WebPostList = res.filter((item) => item.portType == 2)
          await this.getTableDatail(data.standingBookCompanyId)
        })
      },
      //切换table
      changeTable(item) {
        this.titleList.map((item) => (item.selected = false))
        item.selected = true
        this.infoType = item.value
        this.pageData.current = 1
        this.getTableList()
      },
    },
    created() {
      this.initDate()
      this.getTableList()
    },
    mounted() {
      window.onresize = () => {
        return (() => {
          setTimeout(() => {
            this.onresizeHeight =
              window.innerHeight - this.$refs.TableHeight.$el.offsetTop - 80
          }, 10)
        })()
      }
    },
  }
</script>
<style lang='scss' scoped>
  .fieldList {
    padding-left: 14px;
    padding-top: 20px;
    overflow: hidden;
    height: 100%;

    &_title {
      font-size: 18px;
      margin-right: 24px;
      font-weight: 700;
      cursor: pointer;
      padding: 8px 14px 8px 0;
    }

    &_title.actived {
      color: #2d8cf0;
    }

    &_titleList {
      margin-bottom: 20px;
    }

    .pagePublicStyle {
      text-align: right;
      padding: 14px 0;
      margin-right: 30px;
    }

    .totalCount {
      float: left;
      line-height: 34px;
      padding-left: 20px;
    }
  }

  .tabTop {
    ::v-deep .ivu-form-item-label {
      width: 340px !important;
      margin-top: -20px;
    }
  }

  .moudle_cancelButton {
    margin-right: 20px;
  }

  ::v-deep .ivu-tabs {
    overflow: initial;
  }

  .lineLabel {
    float: right;
    margin-right: 0;
  }

  .lineLabelInput {
    width: 140px;
  }

  .lineLabelSpan {
    margin: 0 8px;
  }

  .divider {
    border-top: 1px dashed #ccc;
    margin-top: -6px;
    padding-top: 6px;
  }

  ::v-deep .ivu-tooltip-inner {
    min-height: auto;
    white-space: break-spaces;
  }

  .dispaly_port {
    ::v-deep .ivu-form-item-label {
      width: 100% !important;
      text-align: left;
      padding-left: 70px;
    }

    ::v-deep .ivu-form-item-content {
      margin-left: 90px !important;

      .item_warp {
        display: flex;
        justify-content: flex-start;
        width: 100%;
        flex: 1;

        .item_title {
          margin-right: 20px;
          width: 80px;
        }

        ::v-deep .ivu-checkbox {
          margin-right: 5px !important;
        }
      }
    }
  }
</style>